package com.fast.security.controller;

import com.fast.security.provider.TokenProvider;
import com.fast.common.param.LoginParam;
import com.fast.common.result.ApiHelper;
import com.fast.common.result.ApiResult;
import com.fast.security.user.JwtUserDetails;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Class OpenController
 *
 * @Auther: lhy
 * @Date: 2021/12/7 15:10
 * @Mail: 190643201@qq.com
 */
@AllArgsConstructor
@RestController
@RequestMapping("open")
public class OpenController {

    private final AuthenticationManagerBuilder authenticationManagerBuilder;
    private final TokenProvider tokenProvider;


    @PostMapping("login")
    public ApiResult login(@Validated @RequestBody LoginParam loginParam) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginParam.getUsername(), loginParam.getPassword());
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        JwtUserDetails userDetails = (JwtUserDetails) authentication.getPrincipal();
        boolean rememberMe = loginParam.getRememberMe() == null ? false : loginParam.getRememberMe();
        String token = tokenProvider.createToken(userDetails, rememberMe);
        return ApiHelper.GET_SUCCESS(token);
    }

}
